#include "T_Setting.h"

#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QPlainTextEdit>
#include "ElaComboBox.h"
#include "ElaToggleButton.h"
#include "ElaLineEdit.h"
#include "ElaText.h"
#include "SerialManager.h"
#include <QSerialPortInfo>

#include <QCheckBox>

T_Setting::T_Setting(QWidget* parent)
    : T_BasePage(parent)
{
    ElaComboBox* portCombo = new ElaComboBox(this);
    ElaComboBox* baudCombo = new ElaComboBox(this);
    baudCombo->addItems({"9600", "19200", "38400", "57600", "115200"});

    // 刷新串口列表
    auto refreshPorts = [portCombo]() {
        portCombo->clear();
        for (const QSerialPortInfo& info : QSerialPortInfo::availablePorts()) {
            portCombo->addItem(info.portName());
        }
    };
    refreshPorts();

    ElaToggleButton* toggleBtn = new ElaToggleButton("打开串口", this);
    toggleBtn->setIsToggled(false);

    QHBoxLayout* topLayout = new QHBoxLayout();
    topLayout->addWidget(new ElaText("串口:", this));
    topLayout->addWidget(portCombo);
    topLayout->addWidget(new ElaText("波特率:", this));
    topLayout->addWidget(baudCombo);
    topLayout->addWidget(toggleBtn);

    // 数据显示与交互
    QPlainTextEdit* recvEdit = new QPlainTextEdit(this);
    recvEdit->setReadOnly(true);
    recvEdit->setMinimumHeight(180);

    ElaLineEdit* sendEdit = new ElaLineEdit(this);
    sendEdit->setPlaceholderText("输入要发送的数据...");
    ElaToggleButton* sendBtn = new ElaToggleButton("发送", this);

    // 显示模式切换
    QCheckBox* hexCheck = new QCheckBox("16进制显示", this);

    QHBoxLayout* sendLayout = new QHBoxLayout();
    sendLayout->addWidget(sendEdit);
    sendLayout->addWidget(sendBtn);

    // 串口管理
    SerialManager* serialMgr = new SerialManager(this);

    // 数据缓存
    QByteArray buffer;

    // 信号槽
    connect(toggleBtn, &ElaToggleButton::toggled, this, [=](bool checked) {
        if (checked) {
            serialMgr->open(portCombo->currentText(), baudCombo->currentText().toInt());
            toggleBtn->setText("关闭串口");
        } else {
            serialMgr->close();
            toggleBtn->setText("打开串口");
        }
    });
    connect(sendBtn, &ElaToggleButton::toggled, this, [=]() {
        serialMgr->send(sendEdit->text().toUtf8());
    });

    connect(serialMgr, &SerialManager::received, this, [=](const QByteArray& data) mutable {
        buffer.append(data);

        // 解析完整帧
        while (buffer.size() >= 6) {
            int idx = buffer.indexOf(char(0xAA));
            if (idx < 0 || buffer.size() - idx < 6) break;
            if (buffer.at(idx + 5) == char(0x5A)) {
                // 取温湿度
                quint16 temp = quint8(buffer.at(idx + 1)) << 8 | quint8(buffer.at(idx + 2));
                quint16 hum  = quint8(buffer.at(idx + 3)) << 8 | quint8(buffer.at(idx + 4));
                double tempVal = temp / 100.0;
                double humVal  = hum / 100.0;

                // 显示
                QString text = QString("温度: %1°C  湿度: %2%").arg(tempVal, 0, 'f', 2).arg(humVal, 0, 'f', 2);
                if (hexCheck->isChecked()) {
                    QString hexStr;
                    for (int i = idx; i < idx + 6; ++i)
                        hexStr += QString("%1 ").arg(quint8(buffer.at(i)), 2, 16, QChar('0')).toUpper();
                    recvEdit->appendPlainText(hexStr.trimmed());
                } else {
                    recvEdit->appendPlainText(text);
                }

                // 同步到Home
                emit envDataChanged(QString::number(tempVal, 'f', 2), QString::number(humVal, 'f', 2));

                buffer.remove(0, idx + 6);
            } else {
                buffer.remove(0, idx + 1);
            }
        }
    });

    // 主布局
    QVBoxLayout* mainLayout = new QVBoxLayout();
    mainLayout->addLayout(topLayout);
    mainLayout->addWidget(hexCheck);
    mainLayout->addSpacing(10);
    mainLayout->addWidget(new ElaText("接收区:", this));
    mainLayout->addWidget(recvEdit);
    mainLayout->addWidget(new ElaText("发送区:", this));
    mainLayout->addLayout(sendLayout);
    mainLayout->addStretch();

    QWidget* centralWidget = new QWidget(this);
    centralWidget->setWindowTitle("串口上位机");
    centralWidget->setLayout(mainLayout);
    addCentralWidget(centralWidget, true, true, 0);
}

T_Setting::~T_Setting()
{
}
